import React, { useState } from 'react';
import { Upload, message, Button, Modal } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';

export default function TestPage() {
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const props = {
    // name代表后台接收的文件类型
    name: 'image',
    //点击上传图片时弹窗的默认格式 降低用户上传错误的可能
    accept: '.jpg,.png,.jpeg',
    // action代表上传文件的接口地址
    action: `${baseURL}/v1_0/upload`,
    // 设置tokens
    headers: {
      authorization: `Bearer${getToken()}`,
    },
    onChange(info) {
      // if (info.file.status !== 'uploading') {
      //   console.log(info.file, info.fileList);
      // }
      console.log('info  ---  ', info);
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      console.log('file  ---  ', file);
      setImgUrl(file.thumbUrl);
    },
    beforeUpload(file) {
      // console.log('file  ---  ', file);
      const whiteList = ['image/jpeg', 'image/jpg', 'image/png'];
      if (!whiteList.includes(file.type)) {
        // console.log('不存在  ---  ');
        // 提示用户
        message.warning('不支持的上传格式');
        // 阻止上传 并且不显示
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <>
      {/* 把fileList设置给Upload组件，fileList类似Input的value属性，控制它的值 */}
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {fileList.length < 3 && <Button icon={<UploadOutlined />}></Button>}
      </Upload>
      <Modal
        title="图片预览"
        visible={!!imgUrl}
        onCancel={() => setImgUrl('')}
        footer={null}
      >
        <img width={400} src={imgUrl} alt="" />
      </Modal>
    </>
  );
}
